#! /usr/local/bin/python
# -*- coding: utf-8 -*-

import sys
import os
import re
import time
from sheepomatic import Sheep
import sheepomatic
from sheepomatic_io import Csv_file

from gmail_sender import Gmail_sender

class Tutor_contact_mailer:
   @classmethod
   def get_attrs(cls,conf_tuples):
      sheep_mail_attr = None
      sheep_name_attr = None
      sheep_surname_attr = None
      shepherd_name_attr = None
      shepherd_mail_attr = None
      for attr_name,attr_meaning in conf_tuples:
         if attr_meaning == "sheep_mail":
            sheep_mail_attr = attr_name
         elif attr_meaning == "sheep_name":
            sheep_name_attr = attr_name
         elif attr_meaning == "sheep_surname":
            sheep_surname_attr = attr_name
         elif attr_meaning == "shepherd_name":
            shepherd_name_attr = attr_name
         elif attr_meaning == "shepherd_mail":
            shepherd_mail_attr = attr_name
      if sheep_mail_attr == None:
         print >> sys.stderr, "No sheep_mail in conf file!"
         sys.exit(1)
      elif sheep_name_attr == None:
         print >> sys.stderr, "No sheep_name in conf file!"
         sys.exit(1)
      elif sheep_surname_attr == None:
         print >> sys.stderr, "No sheep_surname in conf file!"
         sys.exit(1)
      elif shepherd_name_attr == None:
         print >> sys.stderr, "No shepherd_name in conf file!"
         sys.exit(1)
      elif shepherd_mail_attr == None:
         print >> sys.stderr, "No shepherd_mail in conf file!"
         sys.exit(1)
      else:
         return sheep_mail_attr,sheep_name_attr,sheep_surname_attr,shepherd_name_attr,shepherd_mail_attr

   @classmethod
   def get_full_addr(cls,sheep_name,sheep_surname,sheep_mail):
      sheep_full_name = sheep_name+" "+sheep_surname
      sheep_full_name = re.sub('[,]', ' ', sheep_full_name)
      return sheep_full_name+" <"+sheep_mail+">"

   @classmethod
   def compile_mail(cls,mail_template_file,sheep_name,\
                                           shepherd_name,shepherd_mail):
      # read template
      f = open(mail_template_file, 'r')
      mail = ""
      for line in f.readlines():
         mail+=line
      f.close()
      mail = re.sub('\[% student_name %\]', sheep_name, mail)
      mail = re.sub('\[% tutor_info %\]', shepherd_name+"\n"+shepherd_mail, mail)
      return mail

   @classmethod
   def read_sent_addrs(cls,sent_addr_log):
      sent_addrs_set = set([])
      # read addrs
      f = open(sent_addr_log, 'r')
      for line in f.readlines():
         line = line.strip()
         sent_addrs_set.add(line)
      f.close()
      return sent_addrs_set

def main(args):
   sheep_filename = args[0]
   attr_conf_filename = args[1]
   mail_template_file = args[2]
   sent_addr_log = args[3]
   # read sheep (with shepherd annotation)
   sheep_list = Csv_file.read_sheep_file(sheep_filename)
   # read conf with transformation of labels (+pivot)
   conf_tuples = sheepomatic.conf_file2tuples(attr_conf_filename)
   sheep_mail_attr,sheep_name_attr,sheep_surname_attr,shepherd_name_attr,shepherd_mail_attr =\
                      Tutor_contact_mailer.get_attrs(conf_tuples)
   #
   sent_addrs_set = Tutor_contact_mailer.read_sent_addrs(sent_addr_log)
   #
   sender = Gmail_sender()
   print >> sys.stderr, "Sending emails,", len(sheep_list), "to send."
   for sheep in sheep_list:
      # prepare information
      sheep_mail = sheep.attr(sheep_mail_attr)
      sheep_name = sheep.attr(sheep_name_attr)
      sheep_surname = sheep.attr(sheep_surname_attr)
      shepherd_name = sheep.attr(shepherd_name_attr)
      shepherd_mail = sheep.attr(shepherd_mail_attr)
      sheep_full_addr = Tutor_contact_mailer.get_full_addr(sheep_name,sheep_surname,sheep_mail)
      sys.stderr.write("   "+sheep_mail+" [" + sheep_full_addr + "]")
      if sheep_mail in sent_addrs_set:
         sys.stderr.write(" SKIPPED\n") 
      else:
         # send the mail
         time.sleep(20)
         message_body = Tutor_contact_mailer.compile_mail(mail_template_file,\
                                                  sheep_name,shepherd_name,shepherd_mail)
         #print message_body
         sender.send_tutoring_message(sheep_full_addr.decode('utf-8'),
                                      "Tutoring and Masaryk University", message_body.decode('utf-8'))
         #
         logfile = open(sent_addr_log,'a')
         print >> logfile, sheep_mail
         sys.stderr.write(" ok\n") 

if __name__ == '__main__':
    args = sys.argv[1:]
    main(args)

